<template>
  <div id="MySale">
    <a-spin :spinning="spinning">
    <div class="filter-box">
      <div class="top-box">
        <Filters
          :form="searchForm"
          :filterData="filterData"
          @confirm="changePage(1)"
        />
        <Btns :data="btns" justify="flex-end" />
      </div>
      <a-tabs v-model="activeName" @change="changeTab">
        <a-tab-pane tab="可上架" key="grounding"></a-tab-pane>
        <a-tab-pane tab="在售" key="sale"></a-tab-pane>
        <a-tab-pane tab="已售" key="out"></a-tab-pane>
      </a-tabs>
    </div>
    <div class="container">
        <!-- <div class="table-item"
          v-for="(item, index) in Data"
          :key="index"
          @click="showDetail(item)"
        >
          <div class="table-left">
            <img :src="item.goodsPic" class="table-img" />
          </div>
          <div class="table-right">
            <a-row :gutter="10">
              <a-col :span="4">{{ item.name }}({{ item.ncMaterielName }})</a-col>
              <a-col :span="4">{{ item.goodsSpec }}</a-col>
              <a-col :span="4">￥{{ item.unitPrice }}元/{{ item.goodsUnit }}</a-col>
              <a-col :span="4">上架数量：{{ item.upNumber }}{{ item.goodsUnit }}</a-col>
              <a-col :span="4">{{ item.provinceName }} {{ item.cityName }}</a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="8">￥{{ item.totalPrice }}</a-col>
              <a-col :span="6" v-if="activeName === 'out'">发货数量：{{ item.sendNum }}{{ item.goodsUnit }}</a-col>
            </a-row>
            <a-row :gutter="10">
              <a-col :span="8">{{ item.ncProjectName }}</a-col>
              <a-col :span="8" v-if="activeName === 'sale'">剩余数量：{{ item.number }}{{ item.goodsUnit }}</a-col>
              <a-col :span="8" v-if="activeName === 'out'">预订人：{{ item.recMan}} {{item.recPhone}}</a-col>
              <a-col :span="8">{{ item.address }}</a-col>
            </a-row>
          </div>
          <div class="table-btn-right" v-if="activeName === 'sale'">
            <a-button type="primary" @click.stop="handleUpDown(item.status, item.goodsId)">{{item.status === 'YSJ' ? '下架' : item.status === 'WSJ' ? '上架' : ''}}</a-button>
            <a-button type="primary" @click.stop="showEdit(item)">编辑</a-button>
          </div>
          <div class="table-btn-right" v-if="activeName === 'out'">
            <a-button type="primary" v-if="['DFH', 'DSH', 'YQX', 'YWC'].includes(item.status)" @click.stop="showDetail(item)">查看详情</a-button>
            <a-button type="primary" v-if="['DFH'].includes(item.status)" @click.stop="sendGoods(item.orderId, item)">发货</a-button>
            <a-button type="primary" v-if="['DFH'].includes(item.status)" @click.stop="cancelHandle(item.orderId)">取消订单</a-button>
          </div>
        </div> -->
      <div  v-if="activeName==='grounding'">
        <div class="search-btn" v-if="firstStep">
          <!-- <div>
            <span>项目筛选 </span>
            <a-select placeholder="全部" allowClear style="width: 300px" @change="changeProject">
              <a-select-option v-for="item in projectList" :key="item.ncProjectId">{{ item.ncProjectName }}
              </a-select-option>
            </a-select>
          </div> -->
          <div>
            <a-button type="primary"  @click.stop="nextStep('first')">批量上架</a-button>
          </div>
        </div>
        <DataTable
        v-if="firstStep"
        :showConfig="false"
        rowKey="goodsId"
        :btns="btn"
        :expand="false"
        :tableData="Data"
        :tableColumn="tableColumn"
        :rowSelection="{ selectedRowKeys: selectedGoods, onChange: changeSelection }"
      >
        <template #expand="{ data }">
          <div class="expand-box">
            <Upload :defaultList="data.countingTaskGoodsFiles" @change="handleUpload" :disabled="true" :limit="6" />
          </div>
        </template>
      </DataTable>
      <DataTable
        v-if="secondStep"
        rowKey="goodsId"
        :btns="editBtns"
        :tableData="editData"
        :expand="true"
        :tableColumn="editTableColumn"
      >
        <template #expand="{ index, data }">
          <div class="expand-box">
            <Upload :defaultList="data.countingTaskGoodsFiles" @change="handleUpload" @click.native="clickUpload(index)" @remove='handleRemove' :limit="6" />
          </div>
        </template>
      </DataTable>
      <div class="page-box" v-if="secondStep">
        <a-button type="primary" @click="nextStep('second')">下一步</a-button>
      </div>
      <div class="last-step" v-if="thirdStep">
        <a-button type="primary" @click="backTop('third')">返回上一步</a-button>
        <a-form-model
          ref="editForm"
          :model="editForm"
          :rules="editRules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <div class="form-row">
             <a-form-model-item label="区域" class="form-col" prop="cityId">
              <a-row :gutter="10">
                <a-col :span="12">
                  <a-select v-model="editForm.provinceId" placeholder="请选择省份" @change="(val) => this.getCity('editForm', val, '')">
                    <a-select-option
                        v-for="option in provinceList"
                        :key="option.value"
                        :value="option.value">
                        {{option.label}}
                  </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="12">
                  <a-select
                    v-model="editForm.cityId"
                    placeholder="请选择"
                  >
                    <a-select-option
                        v-for="option in cityList"
                        :key="option.value"
                        :value="option.value">
                        {{option.label}}
                  </a-select-option>
                  </a-select>
                </a-col>
              </a-row>
            </a-form-model-item>
            <a-form-model-item label="联系电话" class="form-col" prop="linkPhone">
              <a-input
                v-model="editForm.linkPhone"
                placeholder="请输入联系电话"
              />
            </a-form-model-item>
            <a-form-model-item label="联系人" class="form-col" prop="linkMan">
              <a-input v-model="editForm.linkMan" placeholder="请输入联系人" />
            </a-form-model-item>
          </div>
          <div class="form-row">
            <a-form-model-item
              label="详细地址"
              class="form-col"
              prop="address"
            >
              <a-input v-model="editForm.address" placeholder="请输入详细地址" />
            </a-form-model-item>
          </div>
          <div class="form-row">
            <a-form-model-item
              label="物资详情"
              class="form-col"
              prop="goodsDesc"
            >
              <a-input
                v-model="editForm.goodsDesc"
                type="textarea"
                :rows="3"
                placeholder="请输入物资详情"
              />
            </a-form-model-item>
          </div>
        </a-form-model>
        <div class="footer-btns">
          <a-button type="primary" @click="handleBatchUp" v-if="!isEdit">上架</a-button>
          <a-button type="primary" @click="goBack" v-if="isEdit">返回</a-button>
          <a-button type="primary" @click="handleBatchUp" v-if="isEdit">提交</a-button>
        </div>
      </div>
      </div>
      <div class="order-table" v-if="activeName === 'sale'">
        <a-row class="table-header">
          <a-col :span="5">商品</a-col>
          <a-col :span="3">单价</a-col>
          <a-col :span="3" >地区</a-col>
          <a-col :span="3" >总数量</a-col>
          <a-col :span="3">剩余数量</a-col>
          <a-col :span="2">总金额</a-col>
          <a-col :span="3">操作</a-col>
        </a-row>
        <!-- <Sort @change="changeSort"/> -->
        <div
          class="table-item"
          v-for="(item, index) in Data"
          :key="index"
        >
          <a-row class="table-item-desc" type="flex">
            <a-col>项目名称：<b>{{ item.ncProjectName || item.ncGoodsProjectName}}</b></a-col>
            <a-col v-if="activeName === 'sale'">上架时间：{{ item.upTime }}</a-col>
          </a-row>
          <a-row class="table-item-body">
            <a-col :span="5" class="flex-row">
              <img :src="item.goodsPic" class="table-pic" />
              <div class="table-info">
                <p class="info-name-new" v-if="activeName === 'sale'" >{{ item.ncMaterielName }}</p>
                <p class="info-name" v-else @click="showDetail(item)">{{ item.ncMaterielName }}</p>
                <p>规格：{{ item.goodsSpec }}</p>
                <p>单位：{{ item.goodsUnit }}</p>
              </div>
            </a-col>
            <a-col :span="3" class="item-col">
              ￥{{ item.unitPrice }}
            </a-col>
            <a-col :span="3" class="item-col">
              <p>{{ item.provinceName }} {{ item.cityName }}</p>
              <p>{{ item.address }}</p>
            </a-col>
            <a-col :span="3" class="item-col">
              {{ item.number }}
            </a-col>
            <a-col :span="3" class="item-col">
              {{ item.upNumber }}
            </a-col>
            <a-col :span="2" class="item-col">
              ￥{{ item.totalPrice }}
            </a-col>
            <a-col :span="3" class="flex-row">
              <template v-if="activeName === 'sale'">
                <a-button type="primary" size="small" @click="handleUpDown(item.goodsStatus, item.goodsId)">{{item.goodsStatus === 'YSJ' ? '下架' : item.goodsStatus === 'WSJ' ? '上架' : ''}}</a-button>
                <a-button type="primary" size="small" @click="showEdit(item)">编辑</a-button>
              </template>
            </a-col>
          </a-row>
        </div>
        <div class="table-empty" v-if="!Data.length">
          <img src="@/assets/images/empty.png" />
          <span>暂无数据</span>
        </div>
      </div>
      <div class="order-table" v-if="activeName === 'out'">
        <a-row class="table-header">
          <a-col :span="10">商品</a-col>
          <a-col :span="4">预订单价</a-col>
          <a-col :span="4">预订数量</a-col>
          <a-col :span="4">已发货数量</a-col>
        </a-row>
        <div class="search">
          <!-- <Sort @change="changeSort"/> -->
          状态：
          <a-select
            v-model="searchForm.status"
            @change="getList"
            placeholder="请选择"
            size="small"
            allowClear
            class="search-selsect"
          >
            <a-select-option
                v-for="option in statusList"
                :key="option.value"
                :value="option.value">
                {{option.label}}
          </a-select-option>
          </a-select>
        </div>
        <div
          class="table-item"
          v-for="(item, index) in Data"
          :key="index"
        >
          <a-row class="table-item-desc" type="flex" >
            <a-col :span='6'>订单编号：<b>{{ item.shopOrderSn }}</b></a-col>
            <a-col :span='4'>订单合计：￥{{ item.orderTotal }}</a-col>
            <a-col :span='4' class="item-orderStatus">订单状态：{{ changeStatus(item.orderStatus) }}</a-col>
            <a-col class="item-btn" :span='10'>
              <a-button  size="small" class="btns" v-if="['YQX'].includes(item.orderStatus)" @click="delHandle(item.shopOrderTitleId)">删除订单</a-button>
              <a-button  size="small" class="btns" v-if="['DFH'].includes(item.orderStatus)" @click="cancelHandle(item.shopOrderTitleId)">取消订单</a-button>
              <a-button  size="small" class="btns" @click="$router.push({path:'/allot/mySale/detail', query:{shopOrderTitleId: item.shopOrderTitleId}})">订单详情</a-button>
              <a-button  size="small" class="btns" v-if="item.needtalk == 1" @click="$router.push({path:'/allot/mySale/negotiationDetails', query:{shopOrderTitleId: item.shopOrderTitleId}})">商议处理</a-button>
                <a-button type="primary" class="btns" size="small" v-if="['DFH','YFH'].includes(item.orderStatus) && item.showSendBtn" @click="sendGoods(item)">发货</a-button>
            </a-col>
          </a-row>
          <a-row class="table-item-body" v-for="i in item.shopOrders" :key="i.orderId">
            <a-col :span="10" class="flex-row">
              <img :src="i.goodsPic" class="table-pic" />
              <div class="table-info">
                <p class="info-name-new" >{{ i.ncMaterielName }}</p>
                <p>规格：{{ i.goodsSpec }}</p>
                <p>单位：{{ i.goodsUnit }}</p>
              </div>
            </a-col>
            <a-col :span="4" class="item-col">
              ￥{{ i.buyPrice }}
            </a-col>
            <a-col :span="4" class="item-col">
              {{ i.buyNumber }}
            </a-col>
            <a-col :span="4" class="item-col">
              {{ i.sendNum }}
            </a-col>
          </a-row>
        </div>
        <div class="table-empty" v-if="!Data.length">
          <img src="@/assets/images/empty.png" />
          <span>暂无数据</span>
        </div>
      </div>
      <div class="page-box">
        <a-pagination
          v-if="firstStep || activeName === 'out' || activeName === 'sale'"
          size="small"
          :total="pageConfig.total"
          show-quick-jumper
          :show-total="(total) => `总共 ${pageConfig.total} 条数据`"
          @change="changePage"
        />
      </div>
    </div>
    <CommonDialog
      :rows="send.rows"
      :form="sendForm"
      :labelWidth="120"
      title="填写发货信息"
      :visible="sendVisible"
      @hideDialog="sendVisible = false"
      @confirm="confirmSend"
    >
    <template #detail>
        <div class="detail-tit">预定数量： {{orderRow.number}}</div>
        <div class="detail-tit">单价：￥{{orderRow.unitPrice}}/{{orderRow.goodsUnit}}</div>
      </template>
    </CommonDialog>
    <!-- 上架弹框 -->
    <a-modal
      title="上架"
      width="800px"
      :visible="visible"
      okText="上架"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <div class="info-title">基本信息</div>
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <div class="form-row">
          <a-form-model-item label="物资编号" class="form-col" prop="ncMaterielId">
            <!-- <a-select
              v-model="form.ncMaterielId"
              allowClear
              disabled
              placeholder="请选择物资编号"
              @change="(val) => chooseMaterial(val)"
            >
              <a-select-option
                  v-for="option in materialList"
                  :key="option.name"
                  :value="option.id">
                  {{option.id}}
              </a-select-option>
            </a-select> -->
            <a-input v-model="form.ncMaterielId" disabled placeholder="请输入物资编号" />
          </a-form-model-item>
          <a-form-model-item label="物资名称" class="form-col" prop="ncMaterielName">
            <a-input v-model="form.ncMaterielName" disabled placeholder="请输入物资名称" />
          </a-form-model-item>
          <a-form-model-item label="规格" class="form-col">
            <a-input v-model="form.goodsSpec" disabled placeholder="请输入规格" />
          </a-form-model-item>
          <a-form-model-item label="型号" class="form-col" >
            <a-input v-model="form.goodsModel" disabled placeholder="请输入型号" />
          </a-form-model-item>
          <a-form-model-item label="单价" class="form-col" >
            <a-input v-model="form.unitPrice2" disabled placeholder="请输入型号" />
          </a-form-model-item>
          <!-- <a-form-model-item label="采购价格" class="form-col" prop="buyPrice">
            <a-input v-model="form.buyPrice" placeholder="请输入采购价格" />
          </a-form-model-item> -->
          <a-form-model-item label="单位"  class="form-col" >
            <a-select
              disabled
              v-model="form.goodsUnit"
              allowClear
              placeholder="请选择单位"
            >
              <a-select-option
                    v-for="option in unitList"
                    :key="option.value"
                    :value="option.value">
                    {{option.label}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="折扣" class="form-col" prop="discount">
            <a-input-number
              v-model="form.discount"
              placeholder="请输入折扣"
              :formatter="(value) => `${value}%`"
              :parser="(value) => value.replace('%', '')"
              @change="changeDiscount"
            />
          </a-form-model-item>
          <a-form-model-item label="上架价格" class="form-col unitPrice" prop="unitPrice">
            <a-input v-model="form.unitPrice" placeholder="请输入上架价格" @change="changeUnitPrice" />
          </a-form-model-item>

          <a-form-model-item label="上架类型" class="form-col" prop="goodsType">
            <a-select
              v-model="form.goodsType"
              allowClear
              placeholder="请选择"
            >
              <a-select-option
                  v-for="option in typeList"
                  :key="option.label"
                  :value="option.value">
                  {{option.label}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="闲置可调拨数量" class="form-col" prop="number">
            <a-input v-model="form.number" disabled :placeholder="`不能大于可上架数量: ${form.surplusNum}`" />
          </a-form-model-item>
          <a-form-model-item label="上架数量" class="form-col" prop="upNumber">
            <a-input v-model="form.upNumber" :placeholder="`不能大于可闲置可调拨数量: ${form.number}`" />
          </a-form-model-item>
          <!-- <a-form-model-item label="资产类别" class="form-col" prop="goodsKind">
            <a-select
              v-model="form.goodsKind"
              allowClear
              placeholder="请选择"
            >
              <a-select-option
                  v-for="option in kindList"
                  :key="option.label"
                  :value="option.value">
                  {{option.label}}
              </a-select-option>
            </a-select>
          </a-form-model-item> -->
          <a-form-model-item label="区域" class="form-col" prop="cityId">
            <a-row :gutter="10">
              <a-col :span="12">
                <a-select v-model="form.provinceId" placeholder="请选择省份" @change="(val) => this.getCity('form', val, '')">
                  <a-select-option
                      v-for="option in provinceList"
                      :key="option.value"
                      :value="option.value">
                      {{option.label}}
                </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="12">
                <a-select
                  v-model="form.cityId"
                  placeholder="请选择"
                >
                  <a-select-option
                      v-for="option in cityList"
                      :key="option.value"
                      :value="option.value">
                      {{option.label}}
                </a-select-option>
                </a-select>
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item label="联系电话" class="form-col" prop="linkPhone">
            <a-input v-model="form.linkPhone" placeholder="请输入联系电话" />
          </a-form-model-item>
          <a-form-model-item label="联系人" class="form-col" prop="linkMan">
            <a-input v-model="form.linkMan" placeholder="请输入联系人" />
          </a-form-model-item>
        </div>
        <div class="form-row">
          <a-form-model-item label="详细地址" class="form-col" prop="address">
            <a-input v-model="form.address" placeholder="请输入详细地址" />
          </a-form-model-item>
        </div>
        <div class="form-row">
          <a-form-model-item label="物资详情" class="form-col" prop="goodsDesc">
            <a-input
              v-model="form.goodsDesc"
              type="textarea"
              :rows="3"
              placeholder="请输入物资详情"
            />
          </a-form-model-item>
        </div>
      </a-form-model>
      <div class="info-title">资产照片</div>
      <Upload
        :defaultList="goodsPics"
        @change="handleDirectUpload"
        @remove='handleDirectRemove'
        :limit="8"
      />
    </a-modal>
    </a-spin>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import Sort from './components/sort.vue'
import rules from '@/util/rules'
import { Validate } from '@/decorator';
@Component({
  components: {
    Sort
  }
})
export default class Task extends Vue {
  activeName: string = 'grounding';
  visible: boolean = false;
  spinning:boolean= false
  searchForm: any = {
    searchValue: '',
    projectId: undefined,
    status: ''
  };
  form: any = {
    goodsStatus: 'YSJ',
    cityId: undefined,
    provinceId: undefined,
    ncMaterielId: undefined,
    taskDetailId: undefined,
    discount: undefined,
    upNumber: undefined
  };
  goodsPics: any = [] // 资产图片
  btns: any[] = [
    // {
    //   label: '我要上架',
    //   callback: () => this.$router.push('/allot/mySale/grounding')
    // }
  ];

  get filterData () {
    return {
      searchValue: {
        label: '关键词',
        type: 'input',
        template: {
          placeholder: '请输入关键词',
          clearable: true
        }
      },
      projectId: {
        label: '项目筛选',
        type: 'select',
        width: 400,
        template: {
          placeholder: '请选择项目',
          clearable: true,
          filterable: true,
          options: this.projects,
          callback: this.callbackProject,
          popupScroll: this.popupScroll,
          search: this.searchProject
        }
      }

      // status: {
      //   label: '状态',
      //   type: 'select',
      //   tempalte: {
      //     placeholder: '请选择状态',
      //     clearable: true,
      //     filterable: true,
      //     options: [
      //       {
      //         label: '全部',
      //         value: ''
      //       },
      //       {
      //         label: '待发货',
      //         value: 'DFH'
      //       },
      //       {
      //         label: '待收货',
      //         value: 'DSH'
      //       },
      //       {
      //         label: '已完成',
      //         value: 'YWC'
      //       }
      //     ]
      //   }
      // }
    }
  }
  Data: any = [];
  pageConfig: any = {
    current: 1,
    total: 10,
    pageSize: 10
  };
  projects: any = []
  forwardList: any = [] // 发货单位
  warehouses: any = []
  sendVisible = false
  sendForm: any = {
    num: '',
    price: '',
    warehouseId: '',
    project: '',
    orderId: ''
  }
  get send () {
    return {
      rows: {
          detail: {
          slot: true
        },
        num: {
          el: 'inputNumber',
          label: '发货数量',
          placeholder: '请输入',
          rules: [{ required: true, message: '请输入发货数量', trigger: 'blur' }]
        },
        price: {
          label: '发货单价',
          placeholder: '请输入',
          rules: [{ required: true, message: '请输入发货单价', trigger: 'blur' }]
        },
        project: {
          el: 'select',
          label: '发货单位',
          showDisabled: true,
          placeholder: '请选择',
          rules: [{ required: true, message: '请选择发货单位', trigger: 'change' }],
          options: this.forwardList
        },
        warehouseId: {
          el: 'select',
          label: '发货仓库',
          placeholder: '请选择',
          showSearch: true,
          rules: [{ required: true, message: '请选择发货仓库', trigger: 'change' }],
          options: this.warehouses
        }
      }
    }
  }
  orderRow: any = {} // 订单行
  goodsUnitMap: any = {
    'LFM': '立方米',
    'PFM': '平方米',
    'M': '米',
    'D': '吨'
  }
  rules: any = {
    ncMaterielIds: [{ required: true, message: '请选择物料编号', trigger: 'change' }],
    ncMaterielName: [{ required: true, message: '请填写物资名称', trigger: 'blur' }],
    goodsSpec: [{ required: true, message: '请填写规格', trigger: 'blur' }],
    goodsModel: [{ required: true, message: '请填写型号', trigger: 'blur' }],
    buyPrice: [{ required: true, message: '请填写采购价格', trigger: 'blur' }],
    goodsUnit: [{ required: true, message: '请选择单位', trigger: 'change' }],
    discount: [{ required: true, message: '请输入折扣', trigger: 'blur' }],
    unitPrice: [{ required: true, message: '请输入上架价格', trigger: 'blur' }],
    number: [{ required: true, message: '请输入可周转数量', trigger: 'change' }],
    upNumber: [{ required: true, message: '请输入上架数量', trigger: 'change' }],
    goodsType: [{ required: true, message: '请选择上架类型', trigger: 'change' }],
    goodsKind: [{ required: true, message: '请选择资产类型', trigger: 'change' }],
    provinceId: [{ required: true, message: '请选择省份', trigger: 'change' }],
    cityId: [{ required: true, message: '请选择省份', trigger: 'change' }],
    address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
    linkPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { validator: rules.checkPhone(), trigger: 'blur' }
    ],
    linkMan: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    goodsDesc: [{ required: true, message: '请输入物资详情', trigger: 'blur' }],
    ncProjectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }]
  }
  labelCol: Icol = {
    span: 8
  };
  wrapperCol: Icol = {
    span: 14
  };
  selectedRowKeys: any[] = [];
  provinceList: any[] = []
  cityList: any[] = []
  unitList: any = [
    {
      label: '立方米',
      value: 'LFM'
    },
    {
      label: '吨',
      value: 'D'
    },
    {
      label: '米',
      value: 'M'
    },
    {
      label: '平方米',
      value: 'PFM'
    }
  ]
  kindList: any = [
    {
      label: '木方',
      value: 'MF'
    },
    {
      label: '模板',
      value: 'MB'
    },
    {
      label: '竹胶板',
      value: 'ZJB'
    },
    {
      label: '工字钢',
      value: 'GZG'
    },
    {
      label: '标化材料',
      value: 'BHCL'
    }
  ]
  materialList: any = []
  uploadIndex: number = 0 // 上传下标
  selectedGoods: any = []
  goodsList: any[] = []
  editData: any = []
  typeList: any = [
    {
      label: '固定资产',
      value: 'GDZC'
    },
    {
      label: '主材',
      value: 'ZC'
    },
    {
      label: '辅材',
      value: 'FC'
    },
    {
      label: 'A类周转材料(模板支撑)',
      value: 'AZZCL'
    },
    {
      label: 'B类周转材料(料架防护)',
      value: 'BZZCL'
    },
    {
      label: 'C类周转材料(重大设施)',
      value: 'CZZCL'
    },
    {
      label: 'D类周转材料(其他)',
      value: 'DZZCL'
    }
    /* {
      label: '剩余物资',
      value: 'XYWZ'
    },
    {
      label: '办公物品',
      value: 'BGWP'
    } */
  ]
  btn: any[] = [
    // {
    //   label: '批量上架',
    //   callback: () => this.nextStep('first')
    // }
  ]
  editBtns: any[] = [
    {
      label: '返回上一步',
      callback: () => this.backTop('second')
    }
  ];
  tableColumn: any = {

    goodsCode: {
      label: '物资编码',
      width: 120
    },
    projectName: {
      label: '项目名称',
      width: 120
    },
    ncMaterielName: {
      label: '物资名称',
      // slot: true,
      width: 200
    },
    // goodsUnit: {
    //   label: '单位',
    //   width: 120,
    //   map: {
    //     'LFM': '立方米',
    //     'M': '米',
    //     'D': '吨',
    //     'PFM': '平方米'
    //   }
    // },
    goodsSpec: {
      label: '规格',
      width: 120
    },
    goodsModel: {
      label: '型号',
      width: 120
    },
    goodsUnit: {
      label: '单位',
      width: 120
    },
    unitPrice: {
      label: '单价',
      width: 120
    },
    stockNum: {
      label: '库存量',
      width: 120
    },
    surplusNum: {
      label: '闲置可周转量',
      width: 120
    },
    createTime: {
      label: '盘点日期',
      width: 120
    },
    action: {
      label: '操作',
      width: 120,
      fixed: 'right',
      template: [
        {
          tag: 'a',
          text: '上架',
          callback: (row: any) => this.upGoods(row)
        }
      ]
    }
  };
  editTableColumn: any = {
    goodsCode: {
      label: '材料编码',
      width: 120
    },
    ncMaterielName: {
      label: '材料名称'
    },
    // goodsModel: {
    //   label: '型号',
    //   width: 200
    // },
    // goodsSpec: {
    //   label: '规格',
    //   width: 120
    // },
    // goodsUnit: {
    //   label: '单位',
    //   width: 120,
    //   map: {
    //     'LFM': '立方米',
    //     'M': '米',
    //     'D': '吨',
    //     'PFM': '平方米'
    //   }
    // },
    surplusNum: {
      label: '闲置数量',
      width: 120
    },
    discount: {
      label: '折扣',
      type: 'inputNumber',
      width: 120,
      cat: 'percent',
      pre: '%',
      callback: this.changeDiscount2
    },
    unitPrice: {
      label: '上架价格(不含税)',
      type: 'input',
      width: 120,

      callback: this.changeUnitPrice2
    },
    upNumber: {
      label: '可周转数量',
      type: 'inputNumber',
      width: 120,
      max: (row: any) => row.surplusNum
    },
    goodsType: {
      label: '上架类型',
      type: 'select',
      options: [
        {
          label: '固定资产',
          value: 'GDZC'
        },
        {
          label: '主材',
          value: 'ZC'
        },
        {
          label: '辅材',
          value: 'FC'
        },
        {
          label: 'A类周转材料(模板支撑)',
          value: 'AZZCL'
        },
        {
          label: 'B类周转材料(料架防护)',
          value: 'BZZCL'
        },
        {
          label: 'C类周转材料(重大设施)',
          value: 'CZZCL'
        },
        {
          label: 'D类周转材料(其他)',
          value: 'DZZCL'
        }
      ]
    },
    action: {
      label: '操作',
      width: 170,
      fixed: false,
      template: [
        {
          tag: 'a',
          text: '删除',
          callback: (index: number) => this.del(index)
        }
      ]
    }
  };
  editRules: any = {
    cityId: [{ required: true, message: '请选择区域', trigger: 'blur' }],
    address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
    linkPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { validator: rules.checkPhone(), trigger: 'blur' }
    ],
    linkMan: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    goodsDesc: [{ required: true, message: '请输入物资详情', trigger: 'blur' }]
  };
  editForm: any = {
    address: '',
    goodsDesc: '',
    linkMan: JSON.parse(localStorage.getItem('userInfo') || '{}').userName,
    linkPhone: JSON.parse(localStorage.getItem('userInfo') || '{}').userPhone,
    goodsStatus: 'YSJ',
    provinceId: undefined,
    cityId: undefined,
    ncProjectId: undefined
  }
  tt: any = null
  firstStep: boolean = true;
  secondStep: boolean = false;
  thirdStep: boolean = false;
  projectId: undefined;
  searchValue:any = ''
  projectList: any = [] // 项目列表
  statusList:any=[
    {
      label: '全部',
      value: ''
    },
    {
      label: '待发货',
      value: 'DFH'
    },
    {
      label: '已发货',
      value: 'YFH'
    },
    {
      label: '已完成',
      value: 'YWC'
    },
    {
      label: '已取消',
      value: 'YQX'
    }
  ]
  currentPage:any = 1
  get isEdit () {
    return this.$route.query.isEdit === 'edit'
  }
  changeStatus (val:any) {
    let status
      switch (val) {
	  case 'DFH':
	      status = '待发货'
	      break
	  case 'YFH':
	      status = '已发货'
	      break
	  case 'DSH':
	      status = '待收货'
	      break
	  case 'YSH':
	      status = '已收货'
	      break
	  case 'YWC':
	      status = '已完成'
	      break
	  case 'YQX':
	      status = '已取消'
	      break
	  }
	  return status
  }
  init () {
    this.getList()
    this.getProjects()
    this.getProjectList()
    this.getProvince()
    this.getPersonalInfo()
  }
  changeTab () {
    this.Data = []
    this.pageConfig.current = 1
    this.getList()
  }
  changeDiscount2 (row:any) {
    row.unitPrice = Number(Number(row.discount) / 100 * row.unitPrice2).toFixed(2)
  }
  changeUnitPrice2 (row:any) {
    row.discount = Number(Number(row.unitPrice) / Number(row.unitPrice2) * 100).toFixed(2)
  }
  // 改变折扣计算上架价格
  changeDiscount (val:any) {
    this.form.unitPrice = Number(Number(val) / 100 * this.form.unitPrice2).toFixed(2)
  }
  // 改变上架价格计算折扣
  changeUnitPrice (val:any) {
    this.form.discount = Number(Number(val.target.value) / Number(this.form.unitPrice2) * 100).toFixed(2)
  }
  getList () {
    this.spinning = true
    if (this.activeName === 'grounding') {
      let data = {
        page: this.pageConfig.current,
        size: this.pageConfig.pageSize,
        keyword: this.searchForm.searchValue,
        projectId: this.searchForm.projectId ? this.searchForm.projectId.split('-')[0] : ''
      };
      this.$api.goodsCountingListFetch(data).then((res: any) => {
        res.data.records.forEach((ele: any) => {
          ele.countingTaskGoodsFiles = ele.countingTaskGoodsFiles.map((item: any, index: number) => ({
            uid: -index - 1,
            url: item.url,
            name: item.url
          }))
        })
        this.Data = res.data.records

        this.pageConfig.total = res.data.total
        this.spinning = false
      })
    } else {
      let data = {
        page: this.pageConfig.current,
        size: this.pageConfig.pageSize,
        name: this.searchForm.searchValue,
        ncProjectId: this.searchForm.projectId
      };
      let apiFetch = this.$api.goodsMyListFetch
      if (this.activeName === 'out') {
        apiFetch = this.$api.orderMyList2Fetch
        Object.assign(data, {
          type: 'SC',
          status: this.searchForm.status
        })
      }
      apiFetch(data).then((res: any) => {
        res.data.records.forEach((item:any) => {
          if (item.shopOrders) {
            if (item.shopOrders.some((items:any) => items.sendNum < items.buyNumber)) {
              item.showSendBtn = true
            } else {
              item.showSendBtn = false
            }
          }
      })
        this.Data = res.data.records;
        this.pageConfig.total = res.data.total;
        this.spinning = false
        if (!this.Data.length && this.pageConfig.current > 1) {
          --this.pageConfig.current;
          this.getList();
        }
      });
    }
  }
  // 获取用户信息电话联系人
  getPersonalInfo () {
    let data = {
      adminId: JSON.parse(localStorage.getItem('userInfo') || '{}').adminId
    }
    this.$api.memberDetailFetch(data).then((res:any) => {
      this.$set(this.editForm, 'linkMan', res.data.memberName)
      this.$set(this.editForm, 'linkPhone', res.data.memberPhone)
      this.$set(this.form, 'linkMan', res.data.memberName)
      this.$set(this.form, 'linkPhone', res.data.memberPhone)
    })
  }
  searchProject (val:any) {
    this.searchValue = val
    this.currentPage = 1
    this.projects = []
    this.getProjects()
  }
  callbackProject (val:any) {
    this.searchValue = val
    this.currentPage = 1
    this.projects = []
    this.getProjects()
  }
  // 滚动选择框时执行
  popupScroll (e:any) {
    const { scrollHeight, scrollTop, clientHeight } = e.target
      if (Math.floor(scrollHeight - scrollTop) === clientHeight) {
        this.currentPage++
        this.getProjects()
      }
  }
  getProjects () {
    let data = {
      page: this.currentPage,
      size: 100,
      searchValue: this.searchValue
    }
    this.$api.projectRoleProjectListFetch(data).then((res: any) => {
      let projects = this.projects.concat(res.data.records.map((item: any) => ({label: item.ncProjectName, value: item.ncProjectId + '-' + item.ncProjectName, pkOrg: item.pkOrg})))
      this.projects = projects
    })
  }
  // 项目列表
  getProjectList () {
    this.$api.countingGetNcProjectFetch().then((res: any) => {
      this.projectList = res.data
    })
  }
  // 仓库列表
  getWarehouses (pkOrg: any) {
    let data = {
      ncProjectId: this.sendForm.project,
      pkOrg
    }
    this.$api.orderWarehouseListFetch(data).then((res: any) => {
      this.warehouses = res.data.map((item: any) => ({label: item.ncWarehouseName, value: item.ncWarehouseId}))
    })
  }
  // 项目筛选
  changeProject (val: any) {
    this.projectId = val
    this.changePage(1)
  }
  changePage (val: number) {
    this.pageConfig.current = val;
    this.getList();
  }
  searchHandle () {
    this.pageConfig.current = 1;
    this.getList();
  }
  // 删除订单
  delHandle (titleId: any) {
    this.$confirm({
      title: '提示',
      content: '是否删除订单？',
      onOk: () => {
        let data = { titleId, type: 'SC' }
        this.$api.orderDeleteFetch(data).then(() => {
          this.$message.success('删除订单成功')
          this.getList()
        })
      },
      onCancel: () => {}
    })
  }
  showDetail (item: any) {
    this.$router.push({
      path: '/allot/mySale/detail',
      query: { goodsId: item.goodsId, orderId: item.orderId, _alias: 'detail', saleType: this.activeName }
    });
  }
  // 发货
  sendGoods (item: any) {
    this.$router.push({
      path: '/allot/mySale/operate',
      query: {
        shopOrderTitleId: item.shopOrderTitleId,
        salePkOrg: item.salePkOrg,
        saleOrgName: item.saleOrgName,
        saleProjectId: item.saleProjectId,
        saleProjectName: item.saleProjectName
        }
    })
  }
  getOrg (ncProjectId:any) {
    this.$api.orderSelectProjectIdFetch({ncProjectId}).then(res => {
      this.getWarehouses(res.data.pkOrg)
    })
  }
  // 确认发货
  confirmSend () {
    let form = this.sendForm
    this.$api.orderDeliverGoodsFetch(form).then(() => {
      this.$message.success('发货成功')
      this.getList()
      this.sendVisible = false
    })
  }
  // 取消订单
  cancelHandle (titleId: any) {
    this.$confirm({
      title: '提示',
      content: '是否取消订单？',
      onOk: () => {
        let data = { titleId }
        this.$api.orderCancelFetch(data).then(() => {
          this.$message.success('取消订单成功')
          this.getList()
        })
      },
      onCancel: () => {}
    })
  }
  // 上下架商品
  handleUpDown (status: any, goods_id: any) {
    this.$confirm({
      title: '提示',
      content: `${status === 'YSJ' ? '是否下架？' : '是否上架？'}`,
      onOk: () => {
        let data = {
          goods_id,
          type: status === 'YSJ' ? 'WSJ' : status === 'WSJ' ? 'YSJ' : ''
        }
        this.$api.goodsUpOrDownLineFetch(data).then(() => {
          this.$message.success('操作成功')
          this.getList()
        })
      },
      onCancel: () => {}
    })
  }
  // 编辑商品
  showEdit (item: any) {
    this.$router.push({
      path: '/allot/mySale/grounding',
      query: { goodsId: item.goodsId, isEdit: 'edit' }
    });
  }
  // 筛选
  changeSort (type: any, value: number) {
    this.pageConfig.current = 1;
    this.getList()
  }


  getProvince () {
    this.$api.regionProvinceListFetch().then((res: any) => {
      this.provinceList = res.data.map((item: any) => ({label: item.province, value: item.areaId}))
    })
  }
  getCity (form: string, parent_id: any, id: any) {
    this[form].cityId = id || undefined
    this.$api.regionCityListFetch({parent_id}).then((res: any) => {
      this.cityList = res.data.map((item: any) => ({label: item.city, value: item.areaId}))
    })
  }
  handleCancel () {
    this.visible = false;
    this.form = {
      goodsStatus: 'YSJ',
      cityId: undefined,
      provinceId: undefined,
      ncMaterielId: undefined,
      taskDetailId: undefined,
      goodsSpec: undefined,
      goodsModel: undefined,
      goodsUnit: undefined,
      discount: undefined,
      unitPrice: undefined,
      goodsType: undefined,
      number: undefined,
      upNumber: undefined,
      linkMan: JSON.parse(localStorage.getItem('userInfo') || '{}').userName,
      linkPhone: JSON.parse(localStorage.getItem('userInfo') || '{}').userPhone,
      address: undefined,
      goodsDesc: undefined
    }
  }
  handleOk () {}
  // 盘点上架操作的上架
  upGoods (row: any) {
    let { ncMaterielId, ncMaterielName, countingTaskGoodsFiles, surplusNum, taskDetailId, goodsSum, goodsModel, goodsUnit, unitPrice} = row
    this.form.ncMaterielId = ncMaterielId
    this.form.ncMaterielName = ncMaterielName
    this.form.surplusNum = surplusNum
    this.form.number = surplusNum
    this.form.upNumber = surplusNum
    this.form.goodsModel = goodsModel
    this.form.goodsUnit = goodsUnit
    this.form.unitPrice2 = unitPrice
    this.form.discount = ''
    this.form.taskDetailId = taskDetailId
    this.goodsPics = countingTaskGoodsFiles
    this.visible = true


    console.log(this.form);
  }
  // 直接上架商品提交
  // 暂存、提交上级
  @Validate('form')
  handleSubmit () {
    console.log(this.form, 'this.form')
    let { provinceId, cityId, upNumber, ncMaterielId, number, surplusNum } = this.form
    if (!ncMaterielId) {
      return this.$message.error('请选择物资')
    }
    if (!this.goodsPics.length) {
      return this.$message.error('请上传资产照片')
    }
    // if (number > surplusNum) {
    //   return this.$message.error('可周转数量不能大于闲置数量')
    // }
    if (upNumber > number) {
      return this.$message.error('上架数量不能大于闲置可调拨数量')
    }
    let goodsPics = this.goodsPics.map((item: any) => ({
      picUrl: this.$util.getPicUrl(item)
    }))
    let goods = JSON.parse(JSON.stringify(this.form))
    goods.ncMaterielIds = Array.isArray(goods.ncMaterielIds) ? goods.ncMaterielIds.join(',') : goods.ncMaterielIds
    let data = [{
      goods,
      goodsPics
    }]
    this.$api.goodsSaveGoodsFetch(data).then(() => {
      // this.isEdit && this.$message.success(`${this.goodsId ? '编辑成功' : '上架成功'}`)
      // this.isEdit && this.$router.back()
      this.handleCancel() // 盘点上架弹窗关闭
      this.$message.success('上架成功')
      // this.$router.back()
      this.getList()
    })
  }
  handleDirectUpload (fileList: any) {
    this.goodsPics = fileList;
  }
  handleDirectRemove (file:any) {
       this.goodsPics = this.goodsPics.filter((item:any) => {
        return item.url !== file.url;
      })
  }
  // 选择上架
  changeSelection (selectedRowKeys: any, selectedRows: any[]) {
    this.selectedGoods = selectedRowKeys;
    this.editData = selectedRows
    // console.log('1111', selectedRowKeys, selectedRows)
  }
  // 下一步
  nextStep (type: any) {
    if (!this.editData.length) return this.$message.error('请先选择材料')
    console.log('批量上架', this.editData)
    if (type === 'first') {
      this.editData.forEach((ele: any, index: number) => {
        this.$set(this.editData[index], 'unitPrice2', this.editData[index].unitPrice)
        this.$set(this.editData[index], 'unitPrice', 0)
        this.$set(this.editData[index], 'goodsType', '')
        this.$set(this.editData[index], 'discount', 0)
        this.$set(this.editData[index], 'upNumber', this.editData[index].surplusNum)
      })
      this.firstStep = false;
      this.secondStep = true;
      this.thirdStep = false;
    } else if (type === 'second') {
      this.firstStep = false;
      for (let i = 0; i < this.editData.length; i++) {
        if (this.editData[i].countingTaskGoodsFiles.length === 0) return this.$message.error('请上传商品图片')
        if (this.editData[i].unitPrice === 0 || this.editData[i].unitPrice === null) return this.$message.error('请输入上架价格')
        if (this.editData[i].upNumber === 0 || this.editData[i].upNumber === null) return this.$message.error('请输入可周转数量')
        if (this.editData[i].goodsType === '') return this.$message.error('请选择上架类型')
      }
      this.secondStep = false;
      this.thirdStep = true;
    }
  }
  // 上一步
  backTop (type: any) {
    // console.log('1111', type, this.editData);
    if (type === 'second') {
      this.firstStep = true;
      this.secondStep = false;
      this.thirdStep = false;
    } else if (type === 'third') {
      this.firstStep = false;
      this.secondStep = true;
      this.thirdStep = false;
    }
  }
  del (row: any) {
    const key = 'goodsId'
     this.editData.splice(this.editData.findIndex((item:any) => item[key] === row[key]), 1)
  }
  // 点击上传照片
  clickUpload (index: number) {
    this.uploadIndex = index
  }
  // 上传图片
  handleUpload (fileList: any) {
    this.$set(this.editData[this.uploadIndex], 'countingTaskGoodsFiles', fileList)
  }
  // 批量上架
  @Validate('editForm')
  handleBatchUp () {
    let { editData } = this
    let { provinceId, cityId } = this.editForm
    for (var i = 0; i < editData.length; i++) {
        for (var key in editData[i]) {
            if (!editData[i].unitPrice) {
                return this.$message.error('请输入上架价格')
            }
            if (!editData[i].goodsType) {
                return this.$message.error('请选择上架类型');
            }
            if (!editData[i].upNumber) {
                return this.$message.error('请输入可周转数量');
            }
        }
    }
    if (!provinceId || !cityId) {
      return this.$message.error('请选择区域')
    }
    editData = editData.map((ele: any) => {
      delete ele.goodsId
      let goodsPics = ele.countingTaskGoodsFiles.map((item: any) => ({
        picUrl: this.$util.getPicUrl(item)
      }))
      return {
        goodsPics,
        goods: Object.assign(ele, this.editForm, {number: ele.upNumber})
      }
    })
    let data = editData
    this.$api.goodsSaveGoodsFetch(data).then(() => {
      this.$message.success('上架成功')
      this.firstStep = true;
      this.thirdStep = false;
      this.getList()
    })
  }
  test (dataList: any) {
    let dataListNew: any[] = [];
    dataList.forEach((element: any) => {
      dataListNew.push(Object.assign(element, {}));
    });
    return dataListNew;
  }
  handleRemove (file:any) {
    this.editData.forEach((element:any, index:any) => {
       element.countingTaskGoodsFiles = element.countingTaskGoodsFiles.filter((item:any) => {
        return item.url !== file.url;
      })
    });
  }
}
</script>

<style lang="scss">
#MySale {
  .filter-box {
    margin-bottom: 0;
  }
  .ant-tabs-bar {
    margin: 0;
    border-bottom: none;
  }
}
.detail-tit{
  color: #000;
  font-size: 14px;
}
.form-row {
  display: flex;
  flex-wrap: wrap;
  .form-col {
    width: 50%;
    flex-shrink: 0;
    // margin-right: 10px;
    &.col-100 {
      width: 100%;
    }
    .form-tip {
      color: #999;
    }
  }
}
.search-btn{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}
.info-title {
  margin-bottom: 20px;
  font-weight: 600;
  color: #000;
  &::before {
    content: "";
    width: 3px;
    height: 20px;
    background: $themeColor;
    display: inline-block;
    margin-right: 10px;
    vertical-align: middle;
  }
}
.batch-btn{
  margin-bottom: 15px;
}
.grounding{
  margin-bottom: 0 !important;
}
.flex-row{
  display: flex;
  align-items: center;
}
.table-pic{
  width: 94px;
  height: 120px;
}
.info-name-new {
    @include limitLine(2);
    margin-bottom: 16px !important;
    font-size: 14px;
    color: #000;
}
.item-btn{
  text-align: right;
  .btns{
    margin-right: 15px;
  }
}
.table-header{
  text-align: center;
}
.item-col{
  text-align: center;
}
.search{
  display: flex;
  align-items: center;
  .search-selsect{
    width: 150px;
  }
}
.unitPrice{

}
</style>
